package com.fhc.base

import android.content.res.Configuration
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.LocalContext
import androidx.window.layout.WindowMetricsCalculator

//ScreenOrientationHandler { orientation ->
//    when (orientation) {
//        Configuration.ORIENTATION_LANDSCAPE -> LandscapeLayout()
//        Configuration.ORIENTATION_PORTRAIT -> PortraitLayout()
//    }
//}
@Composable
fun ScreenOrientationHandler(content: @Composable (orientation: Int) -> Unit) {
    val configuration = LocalConfiguration.current
    val orientation by rememberUpdatedState(configuration.orientation)

    LaunchedEffect(configuration) {
        snapshotFlow { configuration.orientation }
            .collect { currentOrientation ->
                // 实时获取当前方向
                println("Orientation changed to: $currentOrientation")
            }
    }

    content(orientation)
}

@Composable
fun rememberScreenOrientation(): Int {
    val context = LocalContext.current
    var orientation by remember { mutableIntStateOf(Configuration.ORIENTATION_PORTRAIT) }

    LaunchedEffect(Unit) {
        val windowMetrics = WindowMetricsCalculator.getOrCreate().computeCurrentWindowMetrics(context)
        val bounds = windowMetrics.bounds

        snapshotFlow { windowMetrics } // 监听窗口变化
            .collect {
                orientation = if (bounds.width() > bounds.height()) {
                    Configuration.ORIENTATION_LANDSCAPE
                } else {
                    Configuration.ORIENTATION_PORTRAIT
                }
            }
    }
    return orientation
}

@Composable
fun rememberOrientationWithHistory(): Pair<Int, Int> {
    val context = LocalContext.current
    var previous by remember { mutableIntStateOf(Configuration.ORIENTATION_UNDEFINED) }
    var current by remember { mutableIntStateOf(Configuration.ORIENTATION_PORTRAIT) }

    LaunchedEffect(Unit) {
        WindowMetricsCalculator.getOrCreate()
            .computeCurrentWindowMetrics(context).bounds
            .let { bounds ->
                snapshotFlow { bounds }.collect {
                    previous = current
                    current = if (it.width() > it.height()) {
                        Configuration.ORIENTATION_LANDSCAPE
                    } else {
                        Configuration.ORIENTATION_PORTRAIT
                    }
                }
            }
    }
    return previous to current
}